/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.digitalization.controller;

import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springblade.common.report.ErCodeDs;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tenant.annotation.TenantIgnore;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.digitalization.contant.ConstantDigit;
import org.springblade.modules.digitalization.dto.DaLogDto;
import org.springblade.modules.digitalization.entity.A01Entity;
import org.springblade.modules.digitalization.entity.UmsUserInfoEntity;
import org.springblade.modules.digitalization.excel.A01ArchiveEntity;
import org.springblade.modules.digitalization.manager.LogManager;
import org.springblade.modules.digitalization.service.IA01Service;
import org.springblade.modules.digitalization.service.IUmsUserInfoService;
import org.springblade.modules.digitalization.service.impl.B01ServiceImpl;
import org.springblade.modules.digitalization.vo.UmsUserInfoVO;
import org.springblade.modules.digitalization.wrapper.UmsUserInfoWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

/**
 * 人员基础模型-JAVA 控制器
 *
 * @author RS
 * @since 2022-10-13
 */
@RestController
@AllArgsConstructor
@RequestMapping("digit/ercode")
@Api(value = "人员基础模型-JAVA", tags = "人员基础模型-JAVA接口")
@Slf4j
public class DigUserController extends BladeController {

	private final IUmsUserInfoService umsUserInfoService;
	private final IA01Service ia01Service;
	private List<A01ArchiveEntity> errorData = Lists.newArrayList();
	private final ErCodeDs erCodeDs;
	private final LogManager logManager;


	/**
	 * 人员基础模型-JAVA 详情
	 */
	@ApiLog("刻录")
	@GetMapping("/zipExchange")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入umsUserInfo")
	public R zipExchange(String a0201b) {
		DaLogDto exchangLog = new DaLogDto("刻录");
		exchangLog.setData(a0201b);
		return R.data("success");
	}


	@Autowired
	private B01ServiceImpl b01Service;

	/**
	 * 人员基础模型-JAVA 分页状态码>0的
	 */
	@GetMapping("/erlistAll")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入umsUserInfo")
	public R<IPage<UmsUserInfoVO>> listAll(UmsUserInfoEntity umsUserInfo, Query query) {
		String a0101 = umsUserInfo.getA0101();
		String a0201b = umsUserInfo.getA0201b();
		umsUserInfo.setA0101(null);
		umsUserInfo.setA0201b(null);
		QueryWrapper<UmsUserInfoEntity> queryWrapper = Condition.getQueryWrapper(umsUserInfo);
		if (StringUtil.isNotBlank(a0101)) {
			if (PinyinUtil.isChinese(a0101.charAt(0))) {
				queryWrapper.like("A0101", a0101);
			} else {
				queryWrapper.like("pinyin", a0101.toLowerCase());
			}
		}
		if (StringUtil.isNotBlank(a0201b)) {
			queryWrapper.likeRight("a0201b", a0201b);
		}
		List<Long> authedB01Ids = b01Service.getAuthedB01Ids();
		if (authedB01Ids.isEmpty() == false) {
			queryWrapper.in("b01_id", authedB01Ids);
		}
		queryWrapper.orderByAsc("id");
		IPage<UmsUserInfoEntity> pages = umsUserInfoService.page(Condition.getPage(query), queryWrapper);
		return R.data(UmsUserInfoWrapper.build().pageVO(pages));
	}

	/**
	 * 审核
	 */
	@ApiLog("审核")
	@PostMapping("/aduit")
	public R<String> aduitDa(@Valid @RequestBody A01Entity a01) {
		String result = umsUserInfoService.aduit(a01);
		if (StringUtil.isBlank(result)) {
			return R.data("审核完成");
		} else {
			return R.fail(result);
		}
	}

	@ApiLog("扫描驳回")
	@PostMapping("/scan/refuse")
	public R<String> aduitRefuse(@RequestBody A01Entity a01) {
		String result = umsUserInfoService.scanRefuse(a01);
		return R.data(result);
	}


	@ApiLog("目录驳回")
	@PostMapping("/ml/refuse")
	public R<String> scanRefuse(@RequestBody A01Entity a01) {
		String result = umsUserInfoService.mlRefuse(a01);
		return R.data(result);
	}


	@ApiLog("挂载")
	@PostMapping("/checkMount")
	@ApiOperationSupport(order = 6)
	public R<String> checkMount(@Valid @RequestBody A01Entity a01) {
		String result = umsUserInfoService.checkMount(a01);
		if (Func.isBlank(result)) {
			return R.data(result);
		} else {
			return R.fail(result);
		}
	}


	@PostMapping("/addDa")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入a01")
	public R addDa(@Valid @RequestBody UmsUserInfoEntity umsUserInfo) {
		Boolean aBoolean = umsUserInfoService.saveOneDa(umsUserInfo);
		return R.status(aBoolean);
	}


	/**
	 * 档案同步
	 */
	@ApiLog("档案同步")
	@PostMapping("/syncByExcel")
	@ApiOperationSupport(order = 1)
	@TenantIgnore
	@ApiOperation(value = "通过excel同步档案", notes = "上传excel")
	public R<Boolean> sync(MultipartFile file, String b0111) {
		try {
			umsUserInfoService.doReceiveAsync(file, b0111);
		} catch (ServiceException e) {
			log.error(e.getMessage());
		}
		return R.data(true);
	}

	/**
	 *
	 */
	@ApiLog("入库")
	@PostMapping("/import")
	@ApiOperationSupport(order = 1)
	@TenantIgnore
	@ApiOperation(value = "人员导入", notes = "上传excel")
	public R<List<A01ArchiveEntity>> importA01(MultipartFile file, String b0111, HttpServletResponse response) {
		try {
			List<A01ArchiveEntity> a01ArchiveEntity = umsUserInfoService.doImport(file, b0111);
			errorData = a01ArchiveEntity;

			return R.data(a01ArchiveEntity);
		} catch (Exception e) {
			return R.fail(e.getMessage());
		}
	}

	/**
	 * 导出数据
	 */
	@GetMapping("/exportError")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "导出数据", notes = "传入a01")
	public void exportErrorData(HttpServletResponse response) {
		ExcelUtil.export(response, "错误人员数据" + DateUtil.time(), "错误人员数据", errorData, A01ArchiveEntity.class);
	}

	/**
	 * 人员基础模型-JAVA 新增或修改
	 */
	@PostMapping("/ercodeBu")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入umsUserInfo")
	public R buErCode(@Valid @RequestBody List<A01Entity> a01Entities) {
		Boolean result = erCodeDs.upDateBuCode(a01Entities);

		List<A01Entity> list = Lists.newArrayList();
		a01Entities.stream().forEach(a -> {
			if (a.getStatus() < ConstantDigit.A01_STATUS_ERCODE) {
				a.setStatus(ConstantDigit.A01_STATUS_ERCODE);
				list.add(a);
			}
		});
		if (Func.isNotEmpty(list)) {
			ia01Service.updateBatchById(a01Entities);
			a01Entities.forEach(item -> {
				a01Entities.stream()
					.filter(a -> a.getA0000().equals(item.getA0000())).findFirst().ifPresent(oldData -> {
						logManager.doBizUpdate(item.getA0000(), LogManager.TYPE_A01, "补码", oldData, item);
					});
			});
		}
		return R.status(result);
	}


}
